//
//  AutoLoginViewController.m
//  LocomotiveGuards
//
//  Created by admin on 15/11/17.
//  Copyright (c) 2015年 REDOOR. All rights reserved.
//

#import "AutoLoginViewController.h"
#import "RootviewConrtoller.h"
#import "PopLoadMsg.h"
#import "PopMsg.h"
#import "LoginViewController.h"
#import "APService.h"

@interface AutoLoginViewController ()
{
    UIImageView *backgroundview;
    BOOL start;
    BOOL end;
    NSInteger intforce;
    NSString *newvesionurl;
    UIAlertView *alert0;
    UIAlertView *alert1;
}

@end

@implementation AutoLoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    backgroundview=[[UIImageView alloc]initWithFrame:[UIScreen mainScreen].bounds];
    backgroundview.image=[UIImage imageNamed:@"1pic"];
    [self.view addSubview:backgroundview];
    
    [self dorequestforCheckVersion];
}

-(void)dorequestforCheckVersion{
    NSString *newurl=[urlstring stringByAppendingString:@"checkVersion.do"];
    NSDictionary *dic=@{@"vesionid":CurrentVersion,@"type":@"1"};
    [K_AppDelegate GenerateHTTPRequestWithUrl:newurl withParam:dic success:^(AFHTTPRequestOperation *op,id responseObject){
        NSDictionary *responseDic=(NSDictionary *)responseObject;
      
        
        
        
        NSString *msg=[responseDic objectForKey:@"msg"];
       
        NSString *flag=[responseDic objectForKey:@"flag"];
        NSInteger flag1=[flag longLongValue];
        NSString *force=[responseDic objectForKey:@"isForcedToUpload"];
        intforce=[force integerValue];
        
        if(flag1 == 1){
            newvesionurl=[responseDic objectForKey:@"newVersionUrl"];
            if(intforce==0){
                alert0=[[UIAlertView alloc]initWithTitle:@"当前有新版本,是否需要升级" message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确认", nil];
                
                [alert0 show];
            }
            else if(intforce==1){
                alert1=[[UIAlertView alloc]initWithTitle:@"当前有新版本,需要强制升级" message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:@"确认", nil];
                
                [alert1 show];
                
            }
        }
        else if(flag1==0){
            [self dorequest];
        }
        if(msg){
            NSString *message=[msg stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            //[PopMsg showMessage:message Lasttime:1.0f];
        }
        
        NSLog(@"111");
    }failure:^(AFHTTPRequestOperation *op,NSError *error){
        NSLog(@"222");
       
        [[NSUserDefaults standardUserDefaults]setObject:@"0" forKey:@"judgeNo"];
        self.view.window.rootViewController=[LoginViewController new];
        [PopMsg showMessage:@"网络出错" Lasttime:1.0f];
    }];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    if(alertView==alert0){
        switch (buttonIndex) {
            case 0:
                [self dorequest];
                
                break;
                
            case 1:{
                //[[UIApplication sharedApplication]openURL:[NSURL URLWithString:newvesionurl]];
                NSString *iTunesString = [[NSUserDefaults standardUserDefaults]objectForKey:APP_URL];
                if(iTunesString){
                    NSURL *iTunesURL = [NSURL URLWithString:iTunesString];
                    [[UIApplication sharedApplication] openURL:iTunesURL];
                }
                else{
                    [self dorequest];
                }
                break;
            }

            default:
                break;
        }
    }
    else if(alertView==alert1){
        
        NSString *iTunesString = [[NSUserDefaults standardUserDefaults]objectForKey:APP_URL];
        if(iTunesString){
            NSURL *iTunesURL = [NSURL URLWithString:iTunesString];
            [[UIApplication sharedApplication] openURL:iTunesURL];
        }
        else{
            [self dorequest];
        }
    }
}

-(void)tapped{
    [K_AppDelegate changeRootviewcontroller];
}

-(void)dorequest{
    //自动登录
    start=YES;
    end=YES;
    NSString *forvenderid=[[UIDevice currentDevice].identifierForVendor UUIDString];
    
    PopLoadMsg *loadmsg=[[PopLoadMsg alloc]init];
    //NSString *url=@"http://appif.jszhtech.com:8080/ebappif/appif/login.do";
    NSString *url=[urlstring stringByAppendingString:@"login.do"];
    NSString *phonenumber=[[NSUserDefaults standardUserDefaults]objectForKey:@"phonenumber"];
    
    if(phonenumber==nil){
        phonenumber=@"";
    }
    NSString *pwd=[[NSUserDefaults standardUserDefaults]objectForKey:@"password"];
    
    if(pwd==nil){
        pwd=@"";
    }

    NSDictionary *dic=@{@"loginId":phonenumber,@"loginPwd":pwd,@"type":@"IOS",@"devide":forvenderid,@"registrationId":[APService registrationID]};
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        sleep(startloadtime);
        dispatch_async(dispatch_get_main_queue(), ^{
            if(start==YES){
                [loadmsg loadImages];
            }
        });
    });
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        sleep(startloadtime+endloadtime);
        dispatch_async(dispatch_get_main_queue(), ^{
            end=NO;
            if(start==NO){
                [loadmsg.imageview removeFromSuperview];
            }
        });
    });
    [K_AppDelegate GenerateHTTPRequestWithUrl:url withParam:dic success:^(AFHTTPRequestOperation *op,id responseObject){
        NSLog(@"111");
        start=NO;
        if(end==NO){
            [loadmsg.imageview removeFromSuperview];
        }
        //返回数据是json格式，可以强转NSDictionary;返回数据是二进制，则需要解析
        NSDictionary *responseDic=(NSDictionary *)responseObject;
        NSString *msg=[responseDic objectForKey:@"msg"];
        NSString *flag=[responseDic objectForKey:@"flag"];
        NSInteger flagphone=[flag integerValue];
        if(msg){
            NSString *message=[msg stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            [PopMsg showMessage:message Lasttime:1.0f];
        }
        
        
        
        if(flagphone==0){
            
            NSArray *array=[responseDic objectForKey:@"bidlist"];
            if(array.count!=0 && array!=nil){
                NSDictionary *dic_bid=array[0];
                
                
                NSString *bid=[dic_bid objectForKey:@"bid"];
              
    
                [[NSUserDefaults standardUserDefaults]setObject:bid forKey:@"bid"];
                
            }
            
            else
            {
                
                [PopMsg showMessage:@"不能获得用户注册信息" Lasttime:1.0f];
                return ;
                
                
            }


            //成功登陆
            [[NSUserDefaults standardUserDefaults]setObject:@"1" forKey:@"judgeNo"];
            

            [K_AppDelegate changeRootviewcontroller];
            //self.view.window.rootViewController=[RootviewConrtoller new];

            
        }
        else{
            [[NSUserDefaults standardUserDefaults]setObject:@"0" forKey:@"judgeNo"];
            self.view.window.rootViewController=[LoginViewController new];
        }
        
        
    }failure:^(AFHTTPRequestOperation *op,NSError *error){
        NSLog(@"222");
        start=NO;
        if(end==NO){
            [loadmsg.imageview removeFromSuperview];
        }
        [PopMsg showMessage:@"网络出错" Lasttime:1.0f];
        [[NSUserDefaults standardUserDefaults]setObject:@"0" forKey:@"judgeNo"];
        self.view.window.rootViewController=[LoginViewController new];

    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
